<?php

namespace App\Repository\Db;

use App\Repository\Contracts\NewsInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/7/17 3:09
 */
class NewsRepository extends Repository implements NewsInterface
{
    protected function modelName()
    {
        return 'App\Model\News';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');

        return $this->save($data);
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $data = $query->orderBy('id', 'desc')->with('category')->simplePaginate($limit, ['category_id', 'title', 'cover', 'content', 'is_top', 'created_at'], 'page', $page);
        $list = [];
        foreach ($data as $key => $val) {
            $list[$key] = $val->toArray();
            $list[$key]['created_at'] = date('Y-m-d', strtotime($list[$key]['created_at']));
            $list[$key]['category'] = $val->category->name;
        }

        return $this->simplePaginate('list', $list, $total);
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', '=', $id)->with('category')->get(['category_id', 'title', 'cover', 'content', 'is_top', 'created_at']);
        $data = [];
        foreach ($detail as $key => $value) {
            $data[$key] = $value->toArray();
            $data[$key]['category'] = $value->category->name;
        }

        return $data;
    }

    public function updated($id, array $data)
    {
        $this->validate($data, 'updated');

        return $this->update($data, $id, 'id');
    }
}